/**
 * @date 5:46:39 PM
 * GroupAPIServiceImpl.java
 * Administrator
 * TODO
 */
package com.qs.education.service.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.qs.education.bean.api.PageBean;
import com.qs.education.bean.api.ResponseBean;
import com.qs.education.bean.api.ResponseListBean;
import com.qs.education.bean.beans.EducationGroupResponse;
import com.qs.education.bean.entity.EducationClass;
import com.qs.education.bean.entity.EducationGrade;
import com.qs.education.bean.entity.EducationGroup;
import com.qs.education.bean.entity.EducationSchool;
import com.qs.education.bean.entity.EducationStudent;
import com.qs.education.bean.entity.EducationStudentMessage;
import com.qs.education.bean.entity.EducationTeacher;
import com.qs.education.bean.entity.EducationTeacherMessage;
import com.qs.education.bean.enums.ResponseStatus;
import com.qs.education.bean.service.BaseService;
import com.qs.education.service.IGroupAPIService;

/**
 * @class GroupAPIServiceImpl
 * 
 * @author Warren
 * @description
 * 
 * @date Nov 8, 2018
 */
@Service
public class GroupAPIServiceImpl extends BaseService implements IGroupAPIService {

	/**
	 * @author Warren
	 * @return EducationGroupResponse
	 * @description id为群号(10001开始增长)，根据群号搜索班群
	 * @date Nov 8, 2018
	 */
	@Override
	public EducationGroupResponse searchById(Long id) {
		EducationGroup educationGroup = iEducationGroupDao.get(EducationGroup.class, id);
		EducationGroupResponse educationGroupResponse = new EducationGroupResponse();

		if (educationGroup != null) {
			BeanUtils.copyProperties(educationGroup, educationGroupResponse);
			educationGroupResponse.setStatus(ResponseStatus.SUCCESS.toString());
			return educationGroupResponse;
		}
		educationGroupResponse.setStatus(ResponseStatus.FAILED.toString());
		return educationGroupResponse;
	}

	/**
	 * @author Warren
	 * @param userId 申请的用户id
	 * @param groupId 申请的班群号
	 * @param sendType 申请类型,教师或学生
	 * @return ResponseBean
	 * @description 申请加入班群
	 * @date Nov 19, 2018
	 */
	@Transactional
	@Override
	public ResponseBean apply(Long userId, Long groupId, int sendType) {
		ResponseBean responseBean = new ResponseBean();
		EducationGroup group = iEducationGroupDao.get(EducationGroup.class, groupId);
		if(sendType == 1) {
			int id = Integer.valueOf(Long.toString(userId));
			EducationTeacher teacher = iEducationTeacherDao.get(EducationTeacher.class, id);
			if(group.getTeacher().equals(teacher)) {
				responseBean.setStatus(ResponseStatus.FAILED.toString());
		    	responseBean.setMessage("您是群主，请不要加入自己的班群！");
		    	return responseBean;
			}
			
		    //审核是否已经加入
		    if(group.getTeachers().contains(teacher)) {
		    	responseBean.setStatus(ResponseStatus.FAILED.toString());
		    	responseBean.setMessage("您已经在该班群，请不要重复加入！");
		    	return responseBean;
		    }
		    
		    //审核学校
			EducationSchool school = teacher.getSchool();
		    if(!school.equals(group.getTeacher().getSchool())) {
		    	responseBean.setStatus(ResponseStatus.FAILED.toString());
		    	responseBean.setMessage("申请加入失败，只有同学校的老师或同学可以加入。");
		    	return responseBean;
		    }
		    
		    //群主未处理情况下，审核是否二次申请。
		    EducationTeacherMessage message = iEducationTeacherMessageDao.findEducationTeacherMessageByApplyIdAndStatus(userId, 0);
		    if(message!=null) {
		    	responseBean.setStatus(ResponseStatus.FAILED.toString());
		    	responseBean.setMessage("在群主审核之前请不要重复发送申请！");
		    	return responseBean;
		    }
		    
			//给申请教师发送消息
			EducationTeacherMessage applyTeacherMessage = new EducationTeacherMessage();
			applyTeacherMessage.setMessageStatus(0);
			applyTeacherMessage.setTeacher(teacher);
			applyTeacherMessage.setContent("您加入的"+group.getName()+"班群申请正在审核中");
			iEducationTeacherMessageDao.save(applyTeacherMessage);
			responseBean.setMessage("您加入的"+group.getName()+"班群申请正在审核中");
			
			//给群主教师发送消息
			EducationTeacherMessage teacherMessage = new EducationTeacherMessage();
			teacherMessage.setMessageStatus(0);
			teacherMessage.setGroup(group);
			teacherMessage.setContent(teacher.getName()+"教师申请加入"+group.getName()+"班群，请审核！");
			teacherMessage.setSendType(sendType);
			teacherMessage.setApplyId(userId);
			iEducationTeacherMessageDao.save(teacherMessage);
		}else if(sendType == 2){
			EducationStudent student = iEducationStudentDao.get(EducationStudent.class, userId);
			
			//审核是否已经加入
		    if(group.getStudents().contains(student)) {
		    	responseBean.setStatus(ResponseStatus.FAILED.toString());
		    	responseBean.setMessage("您已经在该班群，请不要重复加入！");
		    	return responseBean;
		    }
		    
			//审核学校
			EducationSchool school = student.getSchool();
		    if(!school.equals(group.getTeacher().getSchool())) {
		    	responseBean.setStatus(ResponseStatus.FAILED.toString());
		    	responseBean.setMessage("申请加入失败，只有同学校的老师或同学可以加入。");
		    	return responseBean;
		    }
			
		    //群主未处理情况下，审核是否二次申请。
		    EducationTeacherMessage message = iEducationTeacherMessageDao.findEducationTeacherMessageByApplyIdAndStatus(userId, 0);
		    if(message!=null) {
		    	responseBean.setStatus(ResponseStatus.FAILED.toString());
		    	responseBean.setMessage("在群主审核之前请不要重复发送申请！");
		    	return responseBean;
		    }
		    
			//给申请学生发送消息
			EducationStudentMessage studentMessage = new EducationStudentMessage();
			studentMessage.setMessageStatus(0);
			studentMessage.setStudent(student);
			studentMessage.setContent("您加入的"+group.getName()+"班群申请正在审核中");
			iEducationStudentMessageDao.save(studentMessage);
			responseBean.setMessage("您加入的"+group.getName()+"班群申请正在审核中");
			
			//给群主教师发送消息
			EducationTeacherMessage teacherMessage = new EducationTeacherMessage();
			teacherMessage.setMessageStatus(0);
			teacherMessage.setGroup(group);
			teacherMessage.setContent(student.getName()+"同学申请加入"+group.getName()+"班群，请审核！");
			teacherMessage.setSendType(sendType);
			teacherMessage.setApplyId(userId);
			iEducationTeacherMessageDao.save(teacherMessage);
			
		}
		responseBean.setStatus(ResponseStatus.SUCCESS.toString());
		return responseBean;
	}

	/**
	 * @Description 根据老师Id 查询老师 所有的 群组
	 * @author Leon
	 * @date Nov 9, 2018
	 * @param
	 * @return List<EducationGroupResponse>
	 */
	@Override
	public ResponseListBean<EducationGroupResponse> findGroupByTeacherId(Integer teacherId) {
		ResponseListBean<EducationGroupResponse> response = new ResponseListBean<EducationGroupResponse>();
		// teacher 查询教师
		EducationTeacher teacher = iEducationTeacherDao.get(EducationTeacher.class, teacherId);
		// groups 查询教师创建的群组
		List<EducationGroup> groups = iEducationGroupDao.findEducationGroupByTeacherId(teacherId);
		if (teacher != null) {

			// groups 将教师 加入的群组和 教师创建的群组合并
			groups.addAll(teacher.getGroups());

			// groups 判断 教师 的 群组 是否为空
			if (groups.size() == 0) {
				response.setStatus(ResponseStatus.FAILED.toString());
				response.setMessage("您还没有任何群组");
				return response;

			} else {
				// groups 循环所有的群组 将 EducationGroup 拷贝到 EducationGroupResponse
				EducationGroupResponse returnresponse = null;
				for (EducationGroup group : groups) {
					returnresponse = new EducationGroupResponse();
					BeanUtils.copyProperties(group, returnresponse);
					response.getList().add(returnresponse);
				}
				response.setStatus(ResponseStatus.SUCCESS.toString());
				return response;
			}
		} else {
			response.setStatus("error");
			response.setMessage("此教师不存在");
			return response;
		}
	}

	/**
	 * @Description 创建多个班群
	 * @author Leon
	 * @date Nov 12, 2018
	 * @param
	 * @return EducationGroupResponse
	 */
	@Transactional
	@Override
	public EducationGroupResponse createGroups(String params) {
		EducationGroupResponse response = new EducationGroupResponse();
		// groups 将Json转化成List<Map<String,Object>>
		List<EducationGroup> groups = new ArrayList<EducationGroup>();
		List<Map> ListMap = JSONArray.parseArray(params, Map.class);
		EducationTeacher teacher = null;
		EducationGrade grade = null;
		EducationClass clazz = null;
		for (Map<String, Object> map : ListMap) {
			Iterator iterator = map.keySet().iterator();
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				Object object = map.get(key);
				if (key.equals("teacherId")) {
					teacher = iEducationTeacherDao.get(EducationTeacher.class, Integer.parseInt(object.toString()));
				}
				if (key.equals("gradeId")) {
					grade = iEducationGradeDao.get(EducationGrade.class, Long.parseLong(object.toString()));
				}
				if (key.equals("classId")) {
					clazz = iEducationClassDao.get(EducationClass.class, Long.parseLong(object.toString()));
				}
			}
			EducationGroup group = new EducationGroup();
			if (teacher != null && grade != null && clazz != null) {
				String name = grade.getName() + clazz.getName();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
				group.setCreateTime(df.format(new Date()));
				group.setTeacher(teacher);
				group.setGrade(grade);
				group.setClazz(clazz);
				group.setName(name);
			}
			groups.add(group);
		}
		try {
			iEducationGroupDao.batchInsert(groups);
			response.setStatus(ResponseStatus.SUCCESS.toString());
			response.setMessage("创建群组成功");
			return response;
		} catch (Exception e) {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("创建群组失败");
			e.printStackTrace();
			return response;
		}
	}

	/**
	 * @Description 移除教师
	 * @author Leon
	 * @date Nov 13, 2018
	 * @param
	 * @return EducationGroupResponse
	 */
	@Transactional
	@Override
	public EducationGroupResponse removeTeacher(String teacherId, String groupId) {
		EducationGroupResponse response = new EducationGroupResponse();
		EducationTeacher teacher = iEducationTeacherDao.get(EducationTeacher.class, Integer.parseInt(teacherId));
		EducationGroup group = iEducationGroupDao.get(EducationGroup.class, Long.parseLong(groupId));
		boolean removeStatus = group.getTeachers().remove(teacher);
		if (removeStatus == false) {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("该用户已不在此群组中");
		} else {
			boolean saveStatus = iEducationGroupDao.save(group);
			if (saveStatus == false) {
				response.setStatus(ResponseStatus.FAILED.toString());
				response.setMessage("移除失败");
			} else {
				response.setStatus(ResponseStatus.SUCCESS.toString());
				response.setMessage("移除成功");
			}
		}
		return response;
	}

	/**
	 * @author Warren
	 * @param id            申请班群消息id
	 * @param messageStatus 教师处理结果
	 * @return ResponseBean
	 * @description 教师处理班群申请
	 * @date Nov 13, 2018
	 */
	@Transactional
	@Override
	public ResponseBean applyHandle(Long id, int messageStatus) {
		ResponseBean responseBean = new ResponseBean();
		EducationTeacherMessage teacherMessage = iEducationTeacherMessageDao.get(EducationTeacherMessage.class, id);
		teacherMessage.setMessageStatus(messageStatus);
		int sendType = teacherMessage.getSendType();
		
		if(messageStatus == 2) {
			//已同意
			EducationGroup group = teacherMessage.getGroup();
			if(sendType == 1) {
				//找到申请教师
				int tid = Integer.valueOf(Long.toString(teacherMessage.getApplyId()));
				EducationTeacher teacher = iEducationTeacherDao.get(EducationTeacher.class, tid);
				teacherMessage.setContent("已通过"+teacher.getName()+"老师申请加入"+teacherMessage.getGroup().getTeacher().getName()+"班群");
				iEducationTeacherMessageDao.update(teacherMessage);
				//把申请教师加入到班群
				List<EducationTeacher> teachers = group.getTeachers();
				teachers.add(teacher);
				iEducationGroupDao.update(group);
				//给申请教师发送结果
				EducationTeacherMessage applyTeacherMessage = new EducationTeacherMessage();
				applyTeacherMessage.setTeacher(teacher);
				applyTeacherMessage.setMessageStatus(0);
				applyTeacherMessage.setContent(teacherMessage.getGroup().getTeacher().getName()+"群主,已同意你加入"+group.getName()+"班群");
				iEducationTeacherMessageDao.save(applyTeacherMessage);
				responseBean.setMessage("已通过"+teacher.getName()+"老师申请加入"+teacherMessage.getGroup().getTeacher().getName()+"班群");
			}else if(sendType == 2){
				//找到申请学生
				EducationStudent student = iEducationStudentDao.get(EducationStudent.class, teacherMessage.getApplyId());
				teacherMessage.setContent("已通过"+student.getName()+"学生申请加入"+teacherMessage.getGroup().getTeacher().getName()+"班群");
				iEducationTeacherMessageDao.update(teacherMessage);
				//把申请教师加入到班群
				List<EducationStudent> students = group.getStudents();
				students.add(student);
				iEducationGroupDao.update(group);
				//给申请学生发送结果
				EducationStudentMessage stduentMessage = new EducationStudentMessage();
				stduentMessage.setStudent(student);
				stduentMessage.setMessageStatus(0);
				stduentMessage.setContent(teacherMessage.getGroup().getTeacher().getName()+"群主,已同意你加入"+group.getName()+"班群");
				iEducationStudentMessageDao.save(stduentMessage);
				responseBean.setMessage("已通过"+student.getName()+"学生申请加入"+teacherMessage.getGroup().getTeacher().getName()+"班群");
			}
		}else if(messageStatus == 3){
			EducationGroup group = teacherMessage.getGroup();
			//不同意
			if(sendType == 1) {
				//找到申请教师
				int tid = Integer.valueOf(Long.toString(teacherMessage.getApplyId()));
				EducationTeacher teacher = iEducationTeacherDao.get(EducationTeacher.class, tid);
				teacherMessage.setContent("已拒绝"+teacher.getName()+"老师申请加入"+teacherMessage.getGroup().getTeacher().getName()+"班群");
				iEducationTeacherMessageDao.update(teacherMessage);
				//给申请教师发送结果
				EducationTeacherMessage applyTeacherMessage = new EducationTeacherMessage();
				applyTeacherMessage.setTeacher(teacher);
				applyTeacherMessage.setMessageStatus(0);
				applyTeacherMessage.setContent(teacherMessage.getGroup().getTeacher().getName()+"群主,已拒绝你加入"+group.getName()+"班群");
				iEducationTeacherMessageDao.save(applyTeacherMessage);
				responseBean.setMessage("已拒绝"+teacher.getName()+"老师申请加入"+teacherMessage.getGroup().getTeacher().getName()+"班群");
			}else if(sendType == 2){
				//找到申请学生
				EducationStudent student = iEducationStudentDao.get(EducationStudent.class, teacherMessage.getApplyId());
				teacherMessage.setContent("已拒绝"+student.getName()+"学生申请加入"+teacherMessage.getGroup().getTeacher().getName()+"班群");
				iEducationTeacherMessageDao.update(teacherMessage);
				//给申请学生发送结果
				EducationStudentMessage stduentMessage = new EducationStudentMessage();
				stduentMessage.setStudent(student);
				stduentMessage.setMessageStatus(0);
				stduentMessage.setContent(teacherMessage.getGroup().getTeacher().getName()+"群主,已拒绝你加入"+group.getName()+"班群");
				iEducationStudentMessageDao.save(stduentMessage);
				responseBean.setMessage("已拒绝"+student.getName()+"学生申请加入"+teacherMessage.getGroup().getTeacher().getName()+"班群");
			}
		}
		return responseBean;
	}

	/**
	 * @author Warren
	 * @param studentId 学生id
	 * @return ResponseListBean<EducationGroup>
	 * @description 根据学生id获取学生的班群列表
	 * @date Nov 13, 2018
	 */
	@Override
	public ResponseListBean<EducationGroup> findGroupByStudentId(Long studentId) {
		ResponseListBean<EducationGroup> responseListBean = new ResponseListBean<EducationGroup>();
		List<EducationGroup> list = iEducationStudentDao.get(EducationStudent.class, studentId).getGroups();
		if (list != null && !list.isEmpty()) {
			responseListBean.setList(list);
		}
		return responseListBean;
	}

	/**
	 * @author Warren
	 * @param ids 移除学生的id集合
	 * @return ResponseBean
	 * @description 批量移除学生
	 * @date Nov 13, 2018
	 */
	@Transactional
	@Override // 获得group的学生列表。
	public ResponseBean removeStudents(String ids, String groupId) {
		EducationGroup educationGroup = iEducationGroupDao.get(EducationGroup.class, Long.parseLong(groupId));
		// 获得group的学生列表。
		List<EducationStudent> students = educationGroup.getStudents();
		ResponseBean responseBean = new ResponseBean();
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			EducationStudent educationStudent = iEducationStudentDao.get(EducationStudent.class,
					Long.valueOf(id.trim()));
			students.remove(educationStudent);
		}
		educationGroup.setStudents(students);
		boolean result = iEducationGroupDao.save(educationGroup);
		if (result) {
			responseBean.setStatus(ResponseStatus.SUCCESS.toString());
			responseBean.setMessage("处理成功");
		} else {
			responseBean.setStatus(ResponseStatus.FAILED.toString());
			responseBean.setMessage("处理失败");
		}
		return responseBean;
	}

	/**
	 * @Description 转让班群
	 * @author Leon
	 * @date Nov 13, 2018
	 * @param
	 * @return EducationGroupResponse
	 */
	@Transactional
	@Override
	public EducationGroupResponse transferGroup(String teacherId, String groupId) {
		EducationGroupResponse response = new EducationGroupResponse();
		EducationTeacher teacher = iEducationTeacherDao.get(EducationTeacher.class, Integer.parseInt(teacherId));
		EducationGroup group = iEducationGroupDao.get(EducationGroup.class, Long.parseLong(groupId));
		group.setTeacher(teacher);
		boolean status = iEducationGroupDao.merge(group);
		if (status == false) {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("转让班群失败，请重新尝试");
		} else {
			BeanUtils.copyProperties(group, response);
			response.setStatus(ResponseStatus.SUCCESS.toString());
			response.setMessage("转让班群成功");
		}
		return response;
	}

	/**
	 * @Description 修改班群
	 * @author Leon
	 * @date Nov 14, 2018
	 * @param
	 * @return EducationGroupResponse
	 */
	@Transactional
	@Override
	public EducationGroupResponse modifyGroup(EducationGroup group) {
		EducationGroupResponse response = new EducationGroupResponse();
		EducationGroup getGroup = iEducationGroupDao.get(EducationGroup.class, group.getId());
		if(group.getHeadImage() != null) {
			getGroup.setHeadImage(group.getHeadImage());
		}
		if(group.getName() != null) {
			getGroup.setName(group.getName());
		}
		if(group.getDescription() != null) {
			getGroup.setDescription(group.getDescription());
		}
		boolean status = iEducationGroupDao.update(getGroup);
		if(status == false) {
			response.setStatus(ResponseStatus.FAILED.toString());
		}else {
			response.setStatus(ResponseStatus.SUCCESS.toString());
		}
		return response;
	}

	/**
	 * @Description 删除班群
	 * @author Leon
	 * @date Nov 14, 2018
	 * @param
	 * @return EducationGroupResponse
	 */
	@Transactional
	@Override
	public EducationGroupResponse deleteGroupById(String groupId) {
		//x 先删除关联 再保存
		//x 再删除群组
		EducationGroupResponse response = new EducationGroupResponse();
		EducationGroup group = iEducationGroupDao.get(EducationGroup.class, Long.parseLong(groupId));
		if (group == null) {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("该群组不存在");
			return response;
		}
		group.getHomeWorkList().clear();
		group.getTeachers().clear();
		group.getStudents().clear();
		boolean saveStatus = iEducationGroupDao.save(group);
		if (saveStatus == false) {
			response.setStatus(ResponseStatus.FAILED.toString());
			response.setMessage("删除失败,请重新尝试");
			return response;
		} else {
			boolean deleteStatus = iEducationGroupDao.delete(group);
			if (deleteStatus == false) {
				response.setStatus(ResponseStatus.FAILED.toString());
				response.setMessage("删除失败,请重新尝试");
				return response;
			} else {
				response.setStatus(ResponseStatus.SUCCESS.toString());
				response.setMessage("删除成功");
				return response;
			}
		}
	}

	@Override
	public PageBean getGroupList(String schoolName, Integer currentPage, Integer pageSize) {

		int recordCount = iEducationGroupDao.getGroupCount(schoolName);
		List<EducationGroup> list = iEducationGroupDao.getGroupList(schoolName,currentPage,pageSize);
		for (EducationGroup group : list) {
			group.setStudents(null);
			group.setHomeWorkList(null);
			group.setTeachers(null);
		}
		PageBean pageBean = new PageBean(currentPage, pageSize, recordCount, list);
		
		return pageBean;
	}
}

